package com.aididi.common.interceptor;

import com.aididi.common.constant.SystemConstant;
import com.aididi.common.entity.CheckResult;
import com.aididi.common.entity.R;
import com.aididi.common.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @ClassName SysInterceptor
 * @Description todo
 * @Author xuzexiang
 * @Data 2019/8/21 17:18
 */
@Slf4j
public class SysInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(handler instanceof HandlerMethod){
            String token = request.getHeader("token");
            if(StringUtils.isEmpty(token)){
                log.info("认证失败");
                print(response, R.error(SystemConstant.JWT_ERRCODE_NULL,"签名验证不存在"));
                return false;
            }else{
                CheckResult result = JwtUtil.validateJwt(token);
                if(result.isSuccess()){
                    return true;
                }else{
                    switch (result.getErrCode()){
                        //验证签名不通过
                        case SystemConstant.JWT_ERRCODE_FAIL:
                            log.info("签名不通过");
                            print(response,R.error(result.getErrCode(),"签名不通过"));
                            break;
                        //验证签名不通过
                        case SystemConstant.JWT_ERRCODE_EXPIRE:
                            log.info("签名过期");
                            print(response,R.error(result.getErrCode(),"签名过期"));
                            break;
                        default:
                             break;
                    }
                    return false;
                }
            }
        }else{
            return true;
        }
    }


    /**
     * @Description 输出请求头内容
     * @return void
     * @param [response, message]
     * @Author xuzexiang
     * @Date 2019/8/21 18:03
     **/
    public void print(HttpServletResponse response,Object message){
        PrintWriter writer = null;
        try {
            response.setStatus(HttpStatus.OK.value());
            response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
            response.setHeader("Cache-Control", "no-cache, must-revalidate");
            writer = response.getWriter();
            writer.write(message.toString());
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (writer != null) {
                writer.close();
            }
        }


    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        if(response.getStatus()==500){
            modelAndView.setViewName("/error/500");
        }else if(response.getStatus()==404){
            modelAndView.setViewName("/error/404");
        }
    }


    /**
     * 该方法也是需要当前对应的Interceptor的preHandle方法的返回值为true时才会执行。该方法将在整个请求完成之后，也就是DispatcherServlet渲染了视图执行，
     * 这个方法的主要作用是用于清理资源的，当然这个方法也只能在当前这个Interceptor的preHandle方法的返回值为true时才会执行。
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
